package com.cqrt.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.log.Log;
import com.cqrt.constant.RTErrorCodeEnum;
import com.cqrt.entity.AuthorityManagementDO;
import com.cqrt.mapper.AuthorityManagementMapper;
import com.cqrt.service.AuthorityManagementService;
import com.cqrt.util.PageDtoUtil;
import com.cqrt.vo.ProjectTypeGroupVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.pdm.iba.service.TyplmAttributeValueService;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.service.snow.SnowflakeIdComponent;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.vo.AttributeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：lotus
 * @DATE: 2025/7/16 21:15
 */
@Service
@Slf4j
public class AuthorityManagementServiceImpl implements AuthorityManagementService {

    @Autowired
    private AuthorityManagementMapper authorityManagementMapper;
    @Resource
    private TyplmAttributeValueService typlmAttributeValueService;
    @Resource
    private SnowflakeIdComponent snowflakeIdComponent;

    @Override
    public void insertAuthority(AuthorityManagementDO authorityManagementDO) {
        List<AuthorityManagementDO> authorityManagementDOS = authorityManagementMapper.selectAuthorityByUid(
                authorityManagementDO.getUserOid());
        if (CollUtil.isNotEmpty(authorityManagementDOS)){
            return;
        }
        TyplmEntityBaseUtil.fillCommonFieldForCreate(authorityManagementDO);
        authorityManagementDO.setOid(snowflakeIdComponent.getInstance().nextId());
        authorityManagementMapper.insertAuthority(authorityManagementDO);
    }

    @Override
    public void updateAuthority(AuthorityManagementDO authorityManagementDO) {
        TyplmEntityBaseUtil.fillCommonFieldForCreate(authorityManagementDO);
        authorityManagementMapper.updateAuthority(authorityManagementDO);
    }

    @Override
    public PageInfo<AuthorityManagementDO> selectAllAuthority(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<AuthorityManagementDO> authorityManagementDO = authorityManagementMapper.selectAllAuthority();
        return new PageInfo<>(authorityManagementDO);

    }

    @Override
    public void deleteAuthorityByOid(BigInteger oid) {

        authorityManagementMapper.deleteAuthority(oid);
    }

    @Override
    public List<AuthorityManagementDO> selectAuthorityByUid(BigInteger uid) {

        return authorityManagementMapper.selectAuthorityByUid(uid);
    }

    @Override
    public PageInfo<UserDO> selectAuthorityUser(String userName, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserDO> userDOS=authorityManagementMapper.selectAuthorityUser(userName);
        return new PageInfo<>(userDOS);
    }

    @Override
    public  List<String> selectAuthorityProjectType() {
        return authorityManagementMapper.selectAuthorityProjectType();
    }

    @Override
    public  Map<String, Map<String, Set<String>>> selectAuthorityProjectIbaAttr() {
        Map<String, Map<String, Set<String>>> resultMap = new HashMap<>();
        List<ProjectTypeGroupVO> typeGroupVOS = authorityManagementMapper.selectAuthorityProjectIbaAttr();
        Map<String, List<BigInteger>> convertToMap = convertToMap(typeGroupVOS);

        for (Map.Entry<String, List<BigInteger>> typeEntry : convertToMap.entrySet()) {
            String projectType = typeEntry.getKey();
            List<BigInteger> projectOids = typeEntry.getValue();
            // 1. 获取该类型下所有项目的IBA属性
            Map<String, List<AttributeVO>> projectAttrMap = typlmAttributeValueService.getAttrValueTableByEntitys(
                    projectOids,
                    TableTypeConstrant.TY_PROJECT_TYPE
            );
            // 2. 构建“属性名称 → 去重非空属性值”的内层Map
            Map<String, Set<String>> attrNameToValues = new HashMap<>();
            projectAttrMap.values().stream()
                    .flatMap(Collection::stream) // 合并所有项目的属性
                    .forEach(attr -> {
                        String attrName = attr.getAttributeName(); // 属性名称
                        String attrValue = attr.getAttributeValue(); // 属性值
                        // 过滤：属性名称和属性值都非空
                        if (StringUtils.isNotEmpty(attrName) && StringUtils.isNotEmpty(attrValue)) {
                            // 若属性名称已存在则直接添加值，否则新建Set
                            attrNameToValues.computeIfAbsent(attrName, k -> new HashSet<>())
                                    .add(attrValue);
                        }
                    });

            resultMap.put(projectType, attrNameToValues);
        }
        return resultMap;
    }


    private Map<String, List<BigInteger>> convertToMap(List<ProjectTypeGroupVO> groups) {
        return groups.stream()
                .collect(Collectors.toMap(
                        ProjectTypeGroupVO::getTypeValue,
                        ProjectTypeGroupVO::getProjectOIDs
                ));
    }
}
